<template>
  <div class="tdt-cesium-container">
    <a class="tools" v-if="rotate" @click="togglePlay" :title="playing ? '暂停自转' : '地球自转'">
      <PlayCircleOutlined v-if="!playing" />
      <PauseCircleOutlined v-if="playing" />
    </a>
    <LayerControl :viewer="viewer" :layers="['imagery', 'terrain']" style="top: 120px" />

    <mapOptions :viewer="viewer" style="right: 7px;left: unset;" />

    <div id="tdt-cesium-container" />
  </div>
</template>

<script>
import { PlayCircleOutlined, PauseCircleOutlined, PlayCircleFilled, PauseCircleFilled } from '@ant-design/icons-vue';

//ref https://www.cnblogs.com/y-y-y-y/p/10441439.html
// http://lbs.tianditu.gov.cn/server/MapService.html
import { defineComponent, ref, onMounted, h } from 'vue';
import * as Cesium from '@cesium/Source/Cesium.js';
import LayerControl from '@funcComp/LayerControl';
import mapOptions from '@funcComp/mapOptions';

import {
  imgTileServiceImageryProviderCreator,
  vecTileServiceImageryProviderCreator,
  terTileServiceImageryProviderCreator,
  ciaTileServiceImageryProviderCreator,
  iboServiceImageryProviderCreator,
  img_tdt_yx,
  img_tdt_sl,
  img_tdt_dx,
  img_tdt_anno,
  img_tdt_ibo,
  imageryProvider
} from '@lib/provider/tdt.js';

const imageryProviderViewModels = [img_tdt_yx(), img_tdt_dx(), img_tdt_sl(), img_tdt_ibo(), img_tdt_anno()];

// Cesium.Camera.DEFAULT_VIEW_FACTOR=0.25//摄像机视口远近参数，可设置地球大小

export default defineComponent({
  name: 'tdt-cesium',
  components: { mapOptions, LayerControl, PlayCircleOutlined, PauseCircleOutlined, PlayCircleFilled, PauseCircleFilled },
  setup(props) {
    return {
      rotater: null
    };
  },
  props: {
    rotate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      viewer: null,
      playing: true
    };
  },
  mounted() {
    Cesium.Ion.defaultAccessToken = $accessToken.default;

    var viewer = new Cesium.Viewer('tdt-cesium-container', {
      selectionIndicator: false,
      animation: false,
      // baseLayerPicker: false,
      // imageryProvider: imgTileServiceImageryProviderCreator(),
      // imageryProviderViewModels, //可供BaseLayerPicker选择的图像图层ProviderViewModel数组
      // selectedImageryProviderViewModel: imageryProviderViewModels[0], //当前地形图层的显示模型，仅baseLayerPicker设为true有意义
      geocoder: false,
      timeline: false,
      navigationHelpButton: false,
      homeButton: false,
      // sceneModePicker: false,
      fullscreenButton: false, //视察全屏按钮
      showRenderLoopErrors: false, //如果设为true，将在一个HTML面板中显示错误信息
      infoBox: false,
      shouldAnimate: true,
      clock: new Cesium.Clock({
        currentTime: Cesium.JulianDate.fromDate(new Date())
      }),
      orderIndependentTranslucency: false,
      contextOptions: {
        webgl: {
          alpha: true
        }
      }
    });

    // viewer.scene.skyBox.show = true;
    // viewer.scene.backgroundColor = new Cesium.Color(0.0, 0.0, 0.0, 0.0);
    viewer.scene.globe.enableLighting = true; //启用以太阳为光源的地球
    viewer.scene.globe.depthTestAgainstTerrain = true;
    //影像标注加载
    viewer.imageryLayers.addImageryProvider(ciaTileServiceImageryProviderCreator());
    viewer.imageryLayers.addImageryProvider(iboServiceImageryProviderCreator());

    this.viewer = viewer;

    // viewer.imageryLayers._layers.forEach(e => (e.show = false));

    //为了能明显的看到，将时针速度设为500倍
    this.initRotater().start({ multiplier: 500 });
  },
  beforeUnmount() {
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  },
  methods: {
    togglePlay() {
      this.playing = !this.playing;
      let { rotater } = this;
      if (this.playing) {
        rotater.start();
      } else {
        rotater.stop();
      }
    },
    initRotater() {
      let vm = this;
      let { viewer } = this;

      function rotater() {
        // 地球自转
        let icrf = function() {
          if (!viewer || viewer.scene.mode !== Cesium.SceneMode.SCENE3D) {
            return;
          }
          const icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(viewer.clock.currentTime);
          if (Cesium.defined(icrfToFixed)) {
            const camera = viewer.camera;
            const offset = Cesium.Cartesian3.clone(camera.position);
            const transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed);
            camera.lookAtTransform(transform, offset);
          }
        };

        this.icrf = icrf;

        //option可以设置时钟的一些参数，比如自转开始的时间，自转的速度等
        this.start = function(option = { multiplier: 500 }) {
          if (!vm.rotate) return;
          viewer.scene.postUpdate.addEventListener(icrf);
          if (viewer.clock) {
            const keys = Object.keys(option);
            for (let k of keys) {
              viewer.clock[k] = option[k];
            }
          }
        };

        this.stop = function() {
          if (!vm.rotate) return;
          if (!viewer) {
            return;
          }
          viewer.clock.multiplier = 1;
          viewer.scene.postUpdate.removeEventListener(icrf);
          // viewer = undefined;
        };
      }

      return (this.rotater = new rotater());
    }
  }
});
</script>

<style lang="less" scoped="">
.tdt-cesium-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .tools {
    position: absolute;
    top: 57px;
    left: 7px;
    font-size: 1.5em;
    padding: 4px 14px;
    color: white;
    z-index: 9999;
    background-color: rgba(40, 48, 60, 1);
    border-radius: 5px;
    opacity: 0.6;
    transition: all 500ms;
    &:hover {
      opacity: 0.8;
    }
  }

  #tdt-cesium-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    :deep(.cesium-viewer-bottom) {
      display: none !important;
    }
  }
}
</style>
